def get_new_sf_time(visit_dates, followup_dates, sfzh,mz_time1):
    from datetime import datetime, timedelta
    import os
    from typing import List, Dict, Set, Optional

    # 创建记录文件
    exceed_file = "执行结果/超过97天间隔记录.txt"
    admin_file = "文档/admin.txt"
    os.makedirs(os.path.dirname(exceed_file), exist_ok=True)  # 确保目录存在

    # 初始化记录文件
    if not os.path.exists(exceed_file):
        with open(exceed_file, "w", encoding="utf-8") as f:
            f.write("身份证号\t操作类型\t日期1\t日期2\t插入日期\t间隔(天)\n")

    # 辅助函数：获取季度
    def get_quarter(date_obj: datetime) -> int:
        return (date_obj.month - 1) // 3 + 1

    # 辅助函数：获取年份
    def get_year(date_obj: datetime) -> int:
        return date_obj.year

    # 读取admin.txt中的时间范围（优先级1）
    try:
        with open(admin_file, 'r', encoding="utf-8") as f:
            text = f.read().split("\n")
            # 清理空行
            text = [line.strip() for line in text if line.strip()]
            start_time = text[4] if len(text) > 4 else "2025-01-01"
            end_time = text[5] if len(text) > 5 else "2025-09-30"
        # 解析为日期对象
        start_date = datetime.strptime(start_time, "%Y-%m-%d")
        end_date = datetime.strptime(end_time, "%Y-%m-%d")

        # 获取年份和该年份的季度范围
        target_year = start_date.year
        start_quarter = get_quarter(start_date)
        end_quarter = get_quarter(end_date)

        # 生成该时间段内的所有季度
        year_quarters = set()
        for q in range(start_quarter, end_quarter + 1):
            year_quarters.add(q)

        print(f"从admin获取的时间范围: {start_time} 至 {end_time}")
        print(f"该时间段内的季度: {sorted(year_quarters)}")
    except Exception as e:
        print(f"读取admin.txt失败: {e}，使用默认时间范围")
        target_year = datetime.now().year
        year_quarters = {1, 2, 3, 4}
        print(f"默认使用当前年份 {target_year} 的所有季度: {sorted(year_quarters)}")


    # 转换日期格式
    try:
        visit_dates_dt: List[datetime] = [datetime.strptime(date, "%Y-%m-%d") for date in visit_dates]
        # 筛选出在目标年份且在时间范围内的门诊日期
        visit_dates_dt = [dt for dt in visit_dates_dt
                          if get_year(dt) == target_year
                          and start_date <= dt <= end_date]
    except Exception as e:
        print(f"转换门诊日期失败: {e}")
        visit_dates_dt = []

    try:
        followup_dates_dt: List[datetime] = [datetime.strptime(date, "%Y-%m-%d") for date in followup_dates]
        # 筛选出在目标年份且在时间范围内的随访日期
        followup_dates_dt = [dt for dt in followup_dates_dt
                             if get_year(dt) == target_year
                             and start_date <= dt <= end_date]
    except Exception as e:
        print(f"转换随访日期失败: {e}")
        followup_dates_dt = []

    # 按季度分类门诊日期（只保留目标年份的）
    quarters: Dict[int, List[datetime]] = {q: [] for q in year_quarters}
    for visit in visit_dates_dt:
        quarter = get_quarter(visit)
        if quarter in quarters:
            quarters[quarter].append(visit)

    # 对每个季度的日期排序
    for q in quarters:
        quarters[q] = sorted(quarters[q])

    # 计算followup_dates中的日期所在季度（优先级2）
    followup_quarters: Set[int] = set()
    for fu in followup_dates_dt:
        q = get_quarter(fu)
        if q in year_quarters:  # 只考虑目标时间段内的季度
            followup_quarters.add(q)
    print("已建随访的季度:", sorted(followup_quarters))

    # 根据1、2筛选出缺失的季度（优先级3）
    missing_quarters: Set[int] = year_quarters - followup_quarters
    print("缺失的季度:", sorted(missing_quarters))

    # 在visit_dates中寻找缺失季度的最早日期（优先级4）
    new_followup_dates: List[datetime] = []
    for quarter in sorted(missing_quarters):
        quarter_visits = quarters.get(quarter, [])
        if quarter_visits:
            # 选择该季度最早的日期
            earliest_date = quarter_visits[0]
            new_followup_dates.append(earliest_date)
            print(f"季度 {quarter} 选择最早日期: {earliest_date.strftime('%Y-%m-%d')}")
        else:
            print(f"季度 {quarter} 没有门诊记录，无法选择日期")

    # 合并新选择的日期与原随访日期（优先级5）
    combined_dates = followup_dates_dt + new_followup_dates
    # 去重并排序
    combined_dates = sorted(list(set(combined_dates)))
    print(f"合并后的日期列表（共{len(combined_dates)}个）: {[d.strftime('%Y-%m-%d') for d in combined_dates]}")

    # 检查相邻日期间隔，超过97天则插入中间日期（优先级6）
    i = 0
    while i < len(combined_dates) - 1:
        current = combined_dates[i]
        next_date = combined_dates[i + 1]
        interval = (next_date - current).days

        if interval > 97:
            print(f"发现间隔 {interval} 天 (>97天)：{current.strftime('%Y-%m-%d')} 至 {next_date.strftime('%Y-%m-%d')}")

            # 计算理想的中间日期
            mid_interval = interval // 2
            ideal_mid_date = current + timedelta(days=mid_interval)

            # 在visit_dates中寻找最接近理想中间日期的日期
            candidates = [dt for dt in visit_dates_dt if current < dt < next_date]
            if candidates:
                # 找到最接近理想中间日期的候选日期
                closest_date = min(candidates, key=lambda x: abs((x - ideal_mid_date).days))
                combined_dates.insert(i + 1, closest_date)
                print(f"插入中间日期: {closest_date.strftime('%Y-%m-%d')}")

                # 记录超过97天的情况
                with open(exceed_file, "a", encoding="utf-8") as f:
                    f.write(
                        f"{sfzh}\t插入中间日期\t{current.strftime('%Y-%m-%d')}\t{next_date.strftime('%Y-%m-%d')}\t"
                        f"{closest_date.strftime('%Y-%m-%d')}\t{interval}\n")
                i += 1  # 跳过新插入的日期
            else:
                print(
                    f"在 {current.strftime('%Y-%m-%d')} 和 {next_date.strftime('%Y-%m-%d')} 之间没有合适的门诊日期可插入")

        i += 1

    # 移除原随访日期，只保留新增的日期（优先级7）
    # 转换为字符串格式以便比较
    followup_str = {d.strftime('%Y-%m-%d') for d in followup_dates_dt}
    result_dates = [d.strftime('%Y-%m-%d') for d in combined_dates
                    if d.strftime('%Y-%m-%d') not in followup_str]
    print(f"仅考虑签约医生,要新建的门诊记录{result_dates}")
    # 最终返回的列表
    end_result = []
    end_result.extend(result_dates)
    # # 如果签约医生门诊缺失季度，从所有的季度中获取，将剩余的季度去除
    followup_dates = [datetime.strptime(date, "%Y-%m-%d") for date in followup_dates]
    followup_dates.extend(result_dates)
    # 获取协议是否使用其他医生的门诊记录
    with open("./执行结果/env.txt", 'r', encoding='utf-8') as file:
        content = file.readlines()
        idf = content[3].replace("：", ":").split(":")[1].strip()
        print("没有签约医生的门诊记录, 是否需要判别包含机构名称字样的其他医生的门诊记录:", idf)

    if idf == "是":
        # 转换日期格式
        try:
            visit_dates_dt: List[datetime] = [datetime.strptime(date, "%Y-%m-%d") for date in mz_time1]
            # 筛选出在目标年份且在时间范围内的门诊日期
            visit_dates_dt = [dt for dt in visit_dates_dt
                              if get_year(dt) == target_year
                              and start_date <= dt <= end_date]
        except Exception as e:
            print(f"转换门诊日期失败: {e}")
            visit_dates_dt = []

        try:
            # followup_str = {d.strftime('%Y-%m-%d') for d in followup_dates_dt}
            new_follow_dates = []
            for date_to_str in followup_dates:
                try:
                    date_new = date_to_str.strftime('%Y-%m-%d')
                    new_follow_dates.append(date_new)
                except:
                    new_follow_dates.append(date_to_str)
            followup_dates_dt: List[datetime] = [datetime.strptime(date, "%Y-%m-%d") for date in new_follow_dates]

            # 筛选出在目标年份且在时间范围内的随访日期
            followup_dates_dt = [dt for dt in followup_dates_dt
                                 if get_year(dt) == target_year
                                 and start_date <= dt <= end_date]
        except Exception as e:
            print(f"转换随访日期失败: {e}")
            followup_dates_dt = []

        # 按季度分类门诊日期（只保留目标年份的）
        quarters: Dict[int, List[datetime]] = {q: [] for q in year_quarters}
        for visit in visit_dates_dt:
            quarter = get_quarter(visit)
            if quarter in quarters:
                quarters[quarter].append(visit)

        # 对每个季度的日期排序
        for q in quarters:
            quarters[q] = sorted(quarters[q])

        # 计算followup_dates中的日期所在季度（优先级2）
        followup_quarters: Set[int] = set()
        for fu in followup_dates_dt:
            q = get_quarter(fu)
            if q in year_quarters:  # 只考虑目标时间段内的季度
                followup_quarters.add(q)
        print("已建随访的季度:", sorted(followup_quarters))

        # 根据1、2筛选出缺失的季度（优先级3）
        missing_quarters: Set[int] = year_quarters - followup_quarters
        print("缺失的季度:", sorted(missing_quarters))

        # 在visit_dates中寻找缺失季度的最早日期（优先级4）
        new_followup_dates: List[datetime] = []
        for quarter in sorted(missing_quarters):
            quarter_visits = quarters.get(quarter, [])
            if quarter_visits:
                # 选择该季度最早的日期
                earliest_date = quarter_visits[0]
                new_followup_dates.append(earliest_date)
                print(f"季度 {quarter} 选择最早日期: {earliest_date.strftime('%Y-%m-%d')}")
            else:
                print(f"季度 {quarter} 没有门诊记录，无法选择日期")

        # 合并新选择的日期与原随访日期（优先级5）
        combined_dates = followup_dates_dt + new_followup_dates
        # 去重并排序
        combined_dates = sorted(list(set(combined_dates)))
        print(f"合并后的日期列表（共{len(combined_dates)}个）: {[d.strftime('%Y-%m-%d') for d in combined_dates]}")

        # 检查相邻日期间隔，超过97天则插入中间日期（优先级6）
        i = 0
        while i < len(combined_dates) - 1:
            current = combined_dates[i]
            next_date = combined_dates[i + 1]
            interval = (next_date - current).days

            if interval > 97:
                print(
                    f"发现间隔 {interval} 天 (>97天)：{current.strftime('%Y-%m-%d')} 至 {next_date.strftime('%Y-%m-%d')}")

                # 计算理想的中间日期
                mid_interval = interval // 2
                ideal_mid_date = current + timedelta(days=mid_interval)

                # 在visit_dates中寻找最接近理想中间日期的日期
                candidates = [dt for dt in visit_dates_dt if current < dt < next_date]
                if candidates:
                    # 找到最接近理想中间日期的候选日期
                    closest_date = min(candidates, key=lambda x: abs((x - ideal_mid_date).days))
                    combined_dates.insert(i + 1, closest_date)
                    print(f"插入中间日期: {closest_date.strftime('%Y-%m-%d')}")

                    # 记录超过97天的情况
                    with open(exceed_file, "a", encoding="utf-8") as f:
                        f.write(
                            f"{sfzh}\t插入中间日期\t{current.strftime('%Y-%m-%d')}\t{next_date.strftime('%Y-%m-%d')}\t"
                            f"{closest_date.strftime('%Y-%m-%d')}\t{interval}\n")
                    i += 1  # 跳过新插入的日期
                else:
                    print(
                        f"在 {current.strftime('%Y-%m-%d')} 和 {next_date.strftime('%Y-%m-%d')} 之间没有合适的门诊日期可插入")

            i += 1

        # 移除原随访日期，只保留新增的日期（优先级7）
        # 转换为字符串格式以便比较
        followup_str = {d.strftime('%Y-%m-%d') for d in followup_dates_dt}
        result_dates2 = [d.strftime('%Y-%m-%d') for d in combined_dates
                        if d.strftime('%Y-%m-%d') not in followup_str]
        print(f"除去签约医生的所有医生的新随访日期{result_dates2}")
        end_result.extend(result_dates2)
    else:
        pass


    print(f"最终生成的新随访日期（共{len(end_result)}个）: {end_result}")

    return [end_date for end_date in set(end_result)]


if __name__ == '__main__':
    sf_sj = get_new_sf_time(["2025-06-03"], ["2025-01-03", "2025-05-03"],
                            "130432200209230930",["2025-03-03", "2025-06-03","2025-09-03"])
    print(sf_sj)